package cn.edu.gduf.luowowo.comment.service.impl;

import cn.edu.gduf.luowowo.comment.domain.QuestionComment;
import cn.edu.gduf.luowowo.comment.repository.QuestionCommentRepository;
import cn.edu.gduf.luowowo.comment.service.IQuestionCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class QuestionCommentServiceImpl implements IQuestionCommentService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private QuestionCommentRepository questionCommentRepository;

    @Override
    public String saveOrUpdate(QuestionComment comment) {
        comment.setCreateTime(new Date());
        if (comment.getType() == QuestionComment.QUESTION_COMMENT_TYPE) {
            String id = comment.getRefComment().getId();
            QuestionComment questionComment = questionCommentRepository.findById(id).get();
            comment.setRefComment(questionComment);
        }
        questionCommentRepository.save(comment);
        return comment.getId();
    }

    @Override
    public List<QuestionComment> selectByQuestionId(Long id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("questionId").is(id));
        return mongoTemplate.find(query, QuestionComment.class);
    }

    @Override
    public QuestionComment findById(String id) {
        return questionCommentRepository.findById(id).get();
    }

    @Override
    public int getCount(Long questionId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("questionId").is(questionId));
        return mongoTemplate.find(query, QuestionComment.class).size();
    }
}
